﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data.Common;
using System.Data.EntityClient;
using System.Data;
using Wicresoft.SMS.Common;


namespace Wicresoft.SMS.Data
{
    internal class sqlDataProvider : IDataProvider, IPushMessageProvider
    {
        private IConnectStringProvider _connParamProvider;



        public sqlDataProvider(IConnectStringProvider configProvider)
        {
            _connParamProvider = configProvider;
        }

        public IEnumerable<SMSRecord> GetMsgToBeSended()
        {
            
            try
            {
                List<SMSRecord> records = new List<SMSRecord>();
                using (var dbModel = new Entities(_connParamProvider.ConnectionString))
                {
                    var msgs = dbModel.cp_query_to_besend();
                    foreach (var msg in msgs)
                    {
                        records.Add(ChangeModel.MessageToSMSRecord(msg));
                    }
                }
                return records;
            }
            catch (Exception ex)
            {
                Logger.Error("GetMsgToBeSended: " + ex.Message.ToString());
                return null;
            }
            

        }

        public List<Email> SetMsgSendingSuccess(List<KeyandMessageId> keyandMessageId)
        {
            if (keyandMessageId == null || keyandMessageId.Count() == 0)
                return null;
            try
            {
                List<Email> emailInfos = new List<Email>();
                using (var dbModel = new Entities(_connParamProvider.ConnectionString))
                {
                    Logger.Debug("Entrying SetMsgSendingSuccess");
                    foreach (var msg in keyandMessageId)
                    {
                        var msgs = dbModel.cp_mark_sendsuccess(msg.MsgIdInDbPrimaryKey,msg.MessageId).ToList<Message>();
                        if (msgs != null)
                        {
                            if (msgs.Count() != 0)
                            {
                                emailInfos.Add(PushEmail(msgs));
                            }
                        }
                    }
                    Logger.Debug("leaving SetMsgSendingSuccess");
                }
                return emailInfos;
            }
            catch (Exception ex)
            {
                Logger.Error("SetMsgSendingSuccess: " + ex.Message.ToString());
                return null;
            }
        }



        public IEnumerable<SMSRecord> GetMsgSending()
        {
            try
            {
                List<SMSRecord> records = new List<SMSRecord>();
                using (var dbModel = new Entities(_connParamProvider.ConnectionString))
                {
                    var msgs = dbModel.cp_query_sending();
                    foreach (var msg in msgs)
                    {
                        records.Add(ChangeModel.MessageToSMSRecord(msg));
                    }
                }
                return records;
            }
            catch (Exception ex)
            {
                Logger.Error("GetMsgSending: " + ex.Message.ToString());
                return null;
            }
            
        }

        public List<Email> SetMsgSendingFailed(List<KeyandMessageId> keyandMessageId)
        {
            if (keyandMessageId == null || keyandMessageId.Count() == 0)
                return null;
            try
            {
                List<Email> emailInfos = new List<Email>();
                using (var dbModel = new Entities(_connParamProvider.ConnectionString))
                {
                    foreach (var msg in keyandMessageId)
                    {
                        var msgs = dbModel.cp_mark_sendfailed(msg.MsgIdInDbPrimaryKey).ToList<Message>();
                        if (msgs != null)
                        {
                            if (msgs.Count() != 0)
                            {
                                emailInfos.Add(PushEmail(msgs));
                            }
                        }
                    }
                }
                return emailInfos;
            }
            catch (Exception ex)
            {
                Logger.Error("SetMsgSendingFailed: " + ex.Message.ToString());
                return null;
            }
        }

        public int SendSMS(string from, string pwd, string text, string to)
        {
            System.Data.Objects.ObjectParameter outs = new System.Data.Objects.ObjectParameter("outs", System.Data.DbType.Int32);
            //int returnstatus = 0;
            try
            {
                using (var dbModel = new Entities(_connParamProvider.ConnectionString))
                {
                    dbModel.cp_send_sms(from, pwd, text, to, outs);
                }
            }
            catch (Exception ex)
            {
                Logger.Debug("SendSMS: " + ex.Message.ToString());
                return -1;
            }
            return Convert.ToInt32(outs.Value);
        }

        

        private Email PushEmail(List<Message> msgs)
        {
            Logger.Debug("Entering PushEmail");
            Email emailInfo = new Email();
            string mainemail =  "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">" +
                                "<html xmlns=\"http://www.w3.org/1999/xhtml\">" +
                                "<head>" +
                                "<title>FailedNotification.htm</title>" +
                                "<style type=\"text/css\">" +
                                ".style2leftcallcolor: #666666;font-size: medium;rightcall" +
                                ".style3leftcallfont-size: small;color: #333333;rightcall" +
                                "pleftcallmargin:6px;font-size:14px;rightcall"+
                                ".style4leftcallfont-family: \"Khmer UI\";font-size: 40px;rightcall" + 
                                "</style>" +
                                "</head>" +
                                "<body style=\"text-align: left\">" +
                                "<p>亲爱的{0}:</p>" +
                                "<p>&nbsp;</p>" +
                                "<p>您在{1}发送至以下号码的短信未发送成功：</p>" +
                                "<p>{2}</p>" +
                                "<p>短信内容为：</p>" +
                                "<p style=\"margin-left: 40px\" class=\"style3\"><span class=\"style4\">&quot;</span>{3}<span class=\"style4\">&quot;</span></p>" +
                                "<p> 请点击<a href=\"{4}\">历史记录</a>查看发送失败短信的详细信息。</p>" +
                                "<p>&nbsp;</p>" +
                                "<p>如果您的电子邮件程序不支持点击“历史记录”，请将此链接粘贴至您的网络浏览器中</p>" +
                                "<p>{4}</p>" +
                                "<p>此邮件为系统自动发送，请勿回复，谢谢合作。</p>" +
                                "<p>&nbsp;</p>" +
                                "<p class=\"style2\">上海贝尔短信平台系统</p>" +
                                "<p class=\"style2\">{5}</p>" +
                                "</body>" +
                                "</html>";
           
            int batchid = 0;
            string sendFailed = String.Empty;
            string content = String.Empty;
            string senttime = String.Empty;
            string to = string.Empty;
            emailInfo.Subject = "Send Messages Failed";
            if (msgs != null && msgs.Count() != 0)
            {
                foreach (var info in msgs)
                {
                    if (emailInfo.To == null || emailInfo.To == String.Empty)
                    {
                        emailInfo.To = GetEmailbyUserID(info.UserID);
                    }
                    if (batchid == 0)
                    {
                        batchid = info.BatchID;
                    }
                    if (content == String.Empty)
                    {
                        content = info.Content;
                    }
                    if (senttime == String.Empty)
                    {
                        senttime = info.CreateTime.ToString("yyyy-MM-dd HH:mm");
                    }
                    if (to == String.Empty)
                    {
                        to = GetUsernmeByUserID(info.UserID);
                    }
                    if(info.State<48 && info.State>=32)
                        sendFailed += info.To.ToString() + "<br/>";
                }
            }

            string url = "tobechangehistory/failed?batchid=" + batchid.ToString();
            emailInfo.Content = String.Format(mainemail, to, senttime, sendFailed, content, url, DateTime.Now.ToString("yyyy-MM-dd HH:mm"));
            Logger.Debug("Leaving PushEmail");
            return emailInfo;
            
        }

        private string GetEmailbyUserID(int userId)
        {
            string email = String.Empty;
            using (var dbModel = new Entities(_connParamProvider.ConnectionString))
            {
                var info = dbModel.User.FirstOrDefault(u => u.UserID == userId);
                if (info != null)
                    email = info.Email;
            }
            return email;

        }

        private string GetUsernmeByUserID(int userId)
        {
            string displayname = String.Empty;
            using (var dbModel = new Entities(_connParamProvider.ConnectionString))
            {
                var info = dbModel.User.FirstOrDefault(u => u.UserID == userId);
                if (info != null)
                    displayname = info.NameEN;
            }
            return displayname;
        }
    }
}
